/**
 * @projectName leetode
 * @package cn.leetcode
 * @className cn.leetcode.t199
 * @copyright Copyright 2020 Thunisoft, Inc All rights reserved.
 */
package cn.leetcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * t199
 * @description 二叉树右视图
 * @author fei
 * @date 2025/9/4 15:13
 * @version 1.0
 */
public class t199 {

    /*
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        List<List<Integer>> levelOrder = getLevelOrder(root);
        for (List<Integer> list : levelOrder) {
            ans.add(list.get(list.size() - 1));
        }
        return ans;
    }

    public static List<List<Integer>> getLevelOrder(TreeNode root){
        List<List<Integer>> res = new ArrayList<>();
        if (root== null){
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            List<Integer> list = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                list.add(node.val);
                if (node.left != null){
                    queue.offer(node.left);
                }
                if (node.right != null){
                    queue.offer(node.right);
                }
            }
            res.add(list);
        }
        return res;
    }
    */

    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        dfs(root, 0, ans);
        return ans;
    }

    public static void dfs(TreeNode root, int depth, List<Integer> ans) {
        if (root == null) {
            return;
        }
        if (depth == ans.size()) {
            ans.add(root.val);
        }
        dfs(root.right, depth + 1, ans);
        dfs(root.left,depth+1, ans);
    }
}
